package edu.cth.speedapp.teacher;


import java.util.LinkedList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.cth.speedapp.DeviceUuidFactory;
import edu.cth.speedapp.HttpRequest;
import edu.cth.speedapp.R;
import edu.cth.speedapp.asynctasks.HTTPAsyncTask;
import edu.cth.speedapp.asynctasks.ITaskCallback;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class TeacherInRoomActivity extends Activity implements ITaskCallback{
	private int tempoOk = 0, 
				   tempoHard = 0, 
				   tempoEasy= 0, 
				   tempoStop= 0; 
	
	private LinearLayout rowStop, rowHard, rowOk, rowEasy;
	
	private String roomName, deviceUuid;
	
	private Timer timer;
	
	private View progress, roomEmptyText;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_in_room);


        // Android device ID
        DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this);
        deviceUuid = deviceUuidFactory.getDeviceUuid().toString();
        
        // Room information
        Bundle extras = getIntent().getExtras();
    	
        if(extras != null ) {
        	roomName = extras.getString("roomName");
        	setTitle(roomName + "  (?)");
        }
    	
    	// Ask for the tempo distribution
        
    
        rowStop = (LinearLayout) findViewById(R.id.rowStop);
        rowHard = (LinearLayout) findViewById(R.id.rowHard);
        rowEasy = (LinearLayout) findViewById(R.id.rowEasy);
        rowOk = (LinearLayout) findViewById(R.id.rowOk);
        
        rowStop.setVisibility(View.INVISIBLE);
        rowHard.setVisibility(View.INVISIBLE);
        rowEasy.setVisibility(View.INVISIBLE);
        rowOk.setVisibility(View.INVISIBLE);
        
        
        progress = findViewById(R.id.teacherStatsProgress);
        progress.setVisibility(View.INVISIBLE);
        
        roomEmptyText = findViewById(R.id.teacherRoomIsEmpty);
        roomEmptyText.setVisibility(View.INVISIBLE);
        
       // updateRoomDistribution("<stop>1<stop/><hard>2<hard/><ok>4<ok/><easy>5<easy/>");
        
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
			getMenuInflater().inflate(R.menu.mode_menue, menu);
	return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()){
			case (R.id.tempoButton):
				Toast.makeText(this, "Already in this mode. ", Toast.LENGTH_SHORT).show();
				break;
			case (R.id.helpButton):


				new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/changeRoomMode.php?roomID=" + roomName + "&&mode=helpqueue");
			
				Intent i = new Intent(this, HelpQueueActivity.class);
				i.putExtra("roomName", roomName);
				
				startActivity(i);
				
				this.finish();
				break;
			case R.id.leaveRoomButton:
					onClickLeaveRoom();
				break;
			case R.id.linkTagButton:
					onClickScanCode();
				break;
		
		}
		return super.onMenuItemSelected(featureId, item);
	}

	
	@Override
	protected void onResume() {
		timer = new Timer();
		try{
			timer.schedule(updateUsersTask, 0, 5000);
		}
		catch(IllegalStateException e){
			
			
		}
		super.onResume();
	}
	@Override
	protected void onPause() {
		super.onPause();
		timer.cancel();
        timer.purge();
        timer = null;
	}
	
	
	public void updateUsersInRoom() {
		handler.sendEmptyMessage(0);
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/getTempoDistribution.php?roomID=" + roomName + "&&androidID=" + deviceUuid);
		
		
		
	}
	
	private Handler handler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	        	progress.setVisibility(View.VISIBLE);
	        }
	};
	
	public void onClickLeaveRoom(){
        // Try to join the room
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/destroyRoom.php?roomID=" + roomName + "&&androidID=" + deviceUuid);
        
        // Close
        finish();
    }
	
	public void onClickScanCode() {
		// TODO get code
		String code = "";
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/connectRoomWithCode.php?roomID=" + roomName + "&&code=" + code);
	}
	

    
	TimerTask updateUsersTask = new TimerTask(){
		@Override
		public void run() {
			updateUsersInRoom();
			
		}
	};


	

	private void updateRoomDistribution(String result){
		progress.setVisibility(View.INVISIBLE);
		
	    
	    Scanner fi = new Scanner(result);
	    //anything other than alphanumberic characters, 
	    //comma, dot or negative sign is skipped
	    fi.useDelimiter("[^\\p{Alnum},\\.-]"); 
	    
	    	/*tempoStop = fi.nextInt();
			tempoHard = fi.nextInt();
			tempoOk =  fi.nextInt();
			tempoEasy = fi.nextInt();*/
	    LinkedList<Integer> numbers = new LinkedList<Integer>();	
	    	
	    while(true){
	        if (fi.hasNextInt()){
	        	numbers.add(fi.nextInt());
	        }
	        else if (fi.hasNext())
	           	fi.next();
	        else
	            break;
	    }
		
		tempoStop = numbers.get(0);
		tempoHard = numbers.get(1);
		tempoOk =   numbers.get(2);
		tempoEasy = numbers.get(3);
		
		int sum = (tempoStop+tempoHard+tempoOk+tempoEasy);
		if(sum > 0){
			rowStop.setVisibility(View.VISIBLE);
	        rowHard.setVisibility(View.VISIBLE);
	        rowEasy.setVisibility(View.VISIBLE);
	        rowOk.setVisibility(View.VISIBLE);
			roomEmptyText.setVisibility(View.INVISIBLE);
			
			 rowStop.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,   
	  	                LayoutParams.WRAP_CONTENT,
	  	                tempoStop+0.1f));
	  	        
  	        rowHard.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,   
  	                LayoutParams.WRAP_CONTENT,
  	                tempoHard+0.1f));
  	        
  	        rowOk.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,   
  	                LayoutParams.WRAP_CONTENT,
  	                tempoOk+0.1f));
  	        
  	        rowEasy.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,   
  	                LayoutParams.WRAP_CONTENT,
  	                tempoEasy+0.1f));
		}else{
			rowStop.setVisibility(View.INVISIBLE);
	        rowHard.setVisibility(View.INVISIBLE);
	        rowEasy.setVisibility(View.INVISIBLE);
	        rowOk.setVisibility(View.INVISIBLE);
			roomEmptyText.setVisibility(View.VISIBLE);
			
		}
		
		
      //  Toast.makeText(this, tempoStop + ", " + tempoHard + ", " + tempoOk + ", " + tempoEasy, Toast.LENGTH_SHORT).show();
        // Updates the LinearView weights
  	       
  	      
  	        
  	      setTitle(roomName + "  (" + sum + ")");
  	    
    }

	
	public void httpTaskCallback(String results) {
		//Toast.makeText(this, "RESULTS: " + results, Toast.LENGTH_SHORT).show();
		Log.d("Tag", roomName);
		if(results.contains("Student count:")){
			Scanner scanner = new Scanner(results);
			setTitle(roomName + "  (" + scanner.nextInt() + ")");
			
		}else if(results.contains("stop")){
			updateRoomDistribution(results);
			
		}else{
			Toast.makeText(this, "Callback could not catch", Toast.LENGTH_SHORT).show();
		
		}
		// TODO Auto-generated method stub
		
	}
}
